﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace Empires.PL.PageBuilder
{
    static class FileLoader
    {
        /// <summary>
        /// 按照文件流的形式读取模板文件,检测编码方式，将所有\\r\\n编码为*r*n
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public static string LoadFile(string filepath)
        {
            if(!File.Exists(filepath))
            {
                throw new FileNotFoundException(String.Format("对于制定路径：{0}的文件未找到", filepath));
            }
            string rawcode = string.Empty;
            using (StreamReader sr = new StreamReader(filepath))
            {
                rawcode = sr.ReadToEnd().Replace("\r\n", "*r*n");
                sr.Close();
            }
            Regex reg = new Regex(PageBuilderRegexpLib.EncodingCheck, RegexOptions.IgnoreCase);
            if (reg.IsMatch(rawcode))
            {
                var encoding = reg.Match(rawcode).Groups[0].ToString();
                if (encoding.ToLower() != Encoding.Default.EncodingName.ToLower()) //如果编码方式不正确则重新读取
                {
                    using (StreamReader sr = new StreamReader(filepath, Encoding.GetEncoding(encoding)))
                    {
                        rawcode = sr.ReadToEnd().Replace("\r\n", "*r*n");
                        sr.Close();
                    }
                }
            }
            reg = new Regex(PageBuilderRegexpLib.EmptyLinkCheck);
            return reg.Replace(rawcode, "");
        }
    }
}
